<?php
namespace App\Http\Controllers\Admin;


use App\Models\Admin\DataProduct;
use App\Models\Factory\DataProductCountFactory;
use App\Models\Factory\DataUserCountFactory;
use App\Models\Orm\DataProductDetailLog;
use App\Models\Orm\DataProductApplyLog;
use App\Models\Orm\XjdUser;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Orm\Productdata;
use Maatwebsite\Excel\Facades\Excel;

/**
 *用户数据
 * Class ProductDataController
 * @package App\Http\Controllers\Controller;
 */
class DataUserController extends Controller
{

    // 导出昨天产品总览
    const EXCEL_YESTERDAY = 0;
    // 导出30天产品总览
    const EXCEL_MONTH = 1;
    // 导出某产品所有日志
    const EXCEL_PRODUCT = 2;

    // 列表页表头
    private $list_excel_header = [
        'app名称',
        '昨天PV',
        '昨天UV',
        '昨天注册人数',
        '昨天登录人数',
    ];

    // 日志页表头
    private $log_excel_header = [
        '记录日期',
        'PV',
        'UV',
        '注册人数',
        '点击人数',
    ];




    /**
     *产品表现数据（展示页）
     * @return \Illuminate\Http\Response
     *
     */
    public function index(Request $request){
        //实例化model
//        $model = new DataProduct();

        $date = $request->input('date', date('Y-m-d'));

        $tab = $request->input('tab', 0);

        if (!$tab) {
            if ($date == date('Y-m-d')) {
                // 今天数据
                $dataList = [];
                // 用户注册数
                $dayUserRegistes = $this->getUserRegiste($date);

                if (!empty($dayUserRegistes)) {

                    foreach ($dayUserRegistes as $dayUserRegiste) {

                        $key = $dayUserRegiste['app_name'];

                        if (!isset($dataList[$key])) {

                            // 初始化这个产品统计记录
                            $dataList[$key] = [
                                'detail_ip_list' => [$dayUserRegiste['created_ip']],
                                'app_name' => $dayUserRegiste['app_name'],
                                'register_pv' => 1,
                                'register_uv' => 1,
                                'register_total' => 1,
                                'login_total'  => 0,
                                'login_pv' =>0,
                                'login_uv' =>0,
                            ];

                        } else {
                            // 更新这个产品统计记录
                            $dataList[$key]['register_total'] += 1;
                            $dataList[$key]['register_pv'] += 1;
                            if (!in_array($dayUserRegiste['created_ip'], $dataList[$key]['detail_ip_list'])) {

                                $dataList[$key]['register_uv'] += 1;
                                $dataList[$key]['detail_ip_list'][] = $dayUserRegiste['created_ip'];

                            }
                        }
                    }
                }

                // 详情页点击日志记录数据
                $dayUserLogins = $this->getUserLogin($date);


                if (!empty($dayUserLogins)) {

                    foreach ($dayUserLogins as $dayUserLogin) {

                        $key = $dayUserLogin['app_name'];

                        if (!isset($dataList[$key])) {

                            // 初始化这个产品统计记录
                            $dataList[$key] = [
                                'detail_ip_list' => [$dayUserLogin['created_ip']],
                                'app_name' => $dayUserLogin['app_name'],
                                'register_total' => 0,
                                'login_total'  => 1,
                                'login_pv' =>1,
                                'login_uv' =>1,
                                'register_pv' => 0,
                                'register_uv' => 0,
                            ];

                        } else {

                            //判断一下当天是否注册过
                            $start = $date . ' 00:00:00';
                            $end = $date . ' 24:00:00';
                            $dayUserLogin['registe_time'];
//                            if($dayUserLogin['registe_time']>$end || $dayUserLogin['registe_time']<$start){
//                                $dataList[$key]['login_total'] += 1;
//                                $dataList[$key]['login_pv'] += 1;

                                if (!in_array($dayUserLogin['created_ip'], $dataList[$key]['detail_ip_list'])) {

                                    $dataList[$key]['login_uv'] += 1;
                                    $dataList[$key]['detail_ip_list'][] = $dayUserLogin['created_ip'];

                                }

//                            }


                        }
                    }
                }

                foreach ($dataList as $key => $item) {
                    unset($dataList[$key]['detail_ip_list']);
                }

               ksort($dataList);


            } else {
                // 某天数据
                $dataList =DataUserCountFactory::getDayDataUserCount($date)->toArray();
            }

            return view('admin.userdata.yesterday', compact('dataList', 'date'));
        }


        // 否则显示30天数据
        $dataList = DataUserCountFactory::getMonthDataUserCount();
        return view('admin.userdata.month', compact('dataList'));
    }
    /**
     * 某一天注册数
     */
    private function getUserRegiste($date)
    {
        $start = $date . ' 00:00:00';
        $end = $date . ' 24:00:00';
        $res = XjdUser::where('registe_time', '>', $start)
            ->where('registe_time', '<=', $end)
            ->where('token', '<>', '')
            ->get()
            ->toArray();
        return $res ?: [];

    }

    /**
     * 某一天登录人数
     */
    private function getUserLogin($date)
    {
        $start = $date . ' 00:00:00';
        $end = $date . ' 24:00:00';
        $res = XjdUser::where('lass_time', '>', $start)
            ->where('lass_time', '<=', $end)
            ->get()
            ->toArray();
        return $res ?: [];

    }

    /**
     * 展示某app数据记录日志
     *
     * @param $product_id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function list($app_name)
    {


        $datas =DataUserCountFactory::getUserCountList($app_name);

        $app_names = config('xianjindai.app_name');
        $app_name = $app_names[$app_name];
        return view('admin.userdata.list', compact('app_name', 'datas'));
    }

    /**
     * 数据导出Excel通用方法
     *
     * @param Request $request
     */
    public function excel(Request $request)
    {
        $tab = $request->input('tab', 0);
        //如果导出某一天数据,获取日期,默认昨天
        $date = $request->input('date', date('Y-m-d'));

        switch ($tab) {
            case self::EXCEL_MONTH :
                // 导出30天产品总览
                $header = $this->list_excel_header;
                $data = DataUserCountFactory::getMonthDataUserCount();
                $file_name = '30天日app总览_' . date('Y-m-d');

                // 组装数据
                $return_data = [$header];

                foreach ($data as $item) {
                    $return_data[] = [
                        config('xianjindai.app_name')[$item->app_name],
                        $item->pv,
                        $item->uv,
                        $item->register_total,
                        $item->login_total,
                    ];
                }

                break;
            case self::EXCEL_PRODUCT :
                // 导出某产品所有日志
                $header = $this->log_excel_header;
                $app_name = $request->input('app_name', 0);
                $app_name = config('xianjindai.app_name')[$app_name];
                $data = DataUserCountFactory::getUserCountList($app_name);
                $file_name = $app_name . '产品日志_' . date('Y-m-d');

                // 组装数据
                $return_data = [$header];

                foreach ($data as $item) {
                    $return_data[] = [
                        $item->create_date,
                        $item->pv,
                        $item->uv,
                        $item->register_total,
                        $item->login_total,
                    ];
                }

                break;
            default :
                // 导出昨天产品总览
                $header = $this->list_excel_header;
                $data = DataUserCountFactory::getDayDataUserCount($date);
                $file_name = '单日日产品总览_' . $date;

                // 组装数据
                $return_data = [$header];

                foreach ($data as $item) {
                    $return_data[] = [
                        config('xianjindai.app_name')[$item->app_name],
                        $item->pv,
                        $item->uv,
                        $item->register_total,
                        $item->login_total,
                    ];
                }
                break;
        }

        // 导出表格
        Excel::create($file_name, function ($excel) use ($return_data) {
            $excel->sheet('score', function ($sheet) use ($return_data) {
                $sheet->rows($return_data);
            });
        })->export('xls');

    }





}